Purpose: Writing programs that use loops, selection and variables.
Goal: Complete as many of these questions as you can. If you are keeping up, you need to do at least the core questions. The additional questions are more challenging and are designed to stretch the more confident programmers. Don't worry if you can't do them now, but be prepared to come back and try them later on.
Marking: All questions are binary marked.
To get a question marked, print out the program(s) you have written and a
cover sheet from the 1b11 web page. Fill in the cover sheet and attach it to the
program listing, then take the work to your lab group demonstrator for marking.
The demonstrator may want to see a demonstration of your program running. An
answer can be submitted as many times as you like, until it is
satisfactory.
All printing should be done on the line printer (a4lp) - don't
use up your laser printer quota!
NOTE: You must keep all marked work as it forms a record of your progress. At the end of the course you are required to re-submit all work.
These exercises require you to write programs that use loops, selection and variables.
Java has three kinds of loop:
a) The while loop
while (boolean-exp) { // Loop body }
The loop body can be executed zero or more times. "boolean-exp" means an expression that evaluates to a boolean value (true or false). When you write a loop you provide a boolean expression appropriate to the loop you are trying to write.
b) The do-while loop
do { // Loop body } while (boolean-exp) ;
The loop body can be executed one or more times. Do loops are used relatively infrequently but do provide a neater solution in situations where the statements in the loop body have to be executed at least once.
c) The for-loop
for ( init-exp ; test-exp ; exp) { // Loop body }
The loop body can be executed zero or more times. For loops are typically used for counting. "init-exp" is an expression evaluated before the loop body is first executed and usually initialises a counter variable. "test-exp" is a boolean expression that is used to decide whether the loop body should be executed. If "test-exp" is true the body is executed, otherwise the loop terminates. "test-exp" is evaluated before the start of every execution of the loop body, not just once. "exp" is an expression evaluated after the loop body has been executed but before "test-exp" is evaluated again. "exp" is used to increment the loop counter.
All the loops have a body bracketed by braces (curley brackets) - make sure you always include the braces. Loop bodies can contain any statement sequence, including nested loops.
Remember that most loops, and certainly those needed by these exercises, must have a properly determined termination condition. This means that one or more statements in the loop body should have some affect on the boolean expression controlling the loop execution. In particular, the expression should evaluate to false within a reasonable number of executions of the loop body.
Selection is provided by the if statement:
if (boolean-exp) { // Statements executed if boolean-exp is true }
This allows the conditional execution of a statement sequence. A variation is the if-else statement:
if (boolean-exp) { // Statements executed if boolean-exp is true } else { // Statements executed if boolean-exp is false }
This allows a choice between two different statement sequences.
Boolean expressions are created using relational and boolean operators. Relational operators are used to compare values such as integers:
a < b- less than a > b - greater than a == b - equal to a <= b - less than or equal to a >= b - greater than or equal to
Boolean operators combine boolean expressions:
a && b - and a || b or !a - negation (not)
Operators can be combined to create more complex boolean expressions:
a < 0 && b > 2
but you need to make sure that the operators are evaluated in the correct order. If in any doubt bracket the sub-expressions:
(a < 0) && (b > 2)
Variables allow values to be stored and manipulated. Variables must be declared and initialised before being used:
int x = 0 ; double b = 1.234 ;
A variable declaration must include a type, while the variable name should attempt to reflect the use of the variable (so one letter variable names such as those above are not ideal! Having said that, loop counter variables are often given a single character name.) A variable name must start with a letter (a-z), followed by any combination of letters and numbers. Punctuation symbols, expect for underscore, are not allowed, and there cannot be spaces in a name. By convention, variable names should start with a lowercase letter.
Integer variables (type int) can be incremented (increased by one) using the operator ++ and decremented (decreased by one) using --:
x++ ; // increment x y-- ; // decrement y
For more detail about loops, the if statement, expressions, operators and variables see chapters 2, 28 and 29 in the text book.
The following are examples of questions and answers, to show how the Java syntax works, and to illustrate the kinds of programs you should be writing. Pay very careful attention to the layout of your program and the use of indentation. Poorly presented code will NOT get a tick when marked.
Example 2.1 Write a program using a while loop to print out a message 10 times. Each message should be on a separate line using this format:
1: A message
2: A message
3: A message
and so on...
Numbering should start from 1. Substitute whatever message you like.
Answer:
Take care to get all those loop conditions and counter increments correct. Easy to make mistakes...
// Written by A.Person, October 2000 // Answer to Ex2 example question 1 class Q2_1 { public static void main(String[] args) { int n = 0 ; while (n < 10) { n = n + 1 ; // or n++ ; System.out.print(n) ; System.out.print(": ") ; System.out.println("Hello World") ; } } }
You can also have less have verbose variations such as:
// Written by A.Person, October 2000 // Alternative answer to Ex2 example question 1 class Q2_1a { public static void main(String[] args) { int n = 0 ; while (n++ < 10) { System.out.println(n + ": Hello World") ; } } }
With both programs note the use of indentation and the way braces have been
lined up. Use of indentation, blank space and blank lines has no effect of the
execution of programs, but their proper use greatly increases readability and
makes mistakes less likely.
Example 2.2 Repeat Example 2.1 using a do loop.
Answer:
// Written by A.Person, October 2000 // Answer to Ex2 example question 2 class Q2_2 { public static void main(String[] args) { int n = 0 ; do { n = n + 1 ; System.out.println(n + ": Hello World") ; } while (n < 10) ; } }
Be careful to get the loop counting correct.
Example 2.3 Repeat Example2.1 using a for loop.
Answer:
// Written by A.Person, October 2000 // Answer to Ex2 example question 3 class Q2_3 { public static void main(String[] args) { for (int n = 0 ; n < 10 ; n++) { System.out.println((n+1) + ": Hello World") ; } } }
Again, watch out for the loop counting.
Example 2.4 Write a program using loops to display the following:
****
****
****
****
You may only print one character at a time.
Hint: nested loops.
Answer:
// Written by A.Person, October 2000 // Answer to Ex2 example question 4 class Q2_4 { public static void main(String[] args) { for (int m = 0 ; m < 4 ; m++) { for (int n = 0 ; n < 4 ; n++) { System.out.print('*') ; } System.out.println("") ; } } }
While loops can be used instead.
You answer all the following questions!
Q2.1 Write a program using a while loop to display the powers of 2 from 1 to 16, like this:
2^1 = 2 2^2 = 4 2^3 = 8
and so on.
Note: the multiplication operator is * (2 * 2 = 4).
How can you calculate powers of 2 efficiently? Hint: 2^3 = (2^2)*2
Q2.2 Repeat Q2.1 using a do loop.
Q2.3 Repeat Q2.1 using a for loop.
Q2.4 Write a program using loops to display the following:
**** **** **** ****
You may display only one character at a time.
Hint: nested loops.
Q2.5 Write a program using loops to display the following:
* ** *** **** ***** ******
You may display only one character at a time.
Q2.6 Write a program using loops to display the following:
***** ***** ***** ***** ***** ***** *****
You may display only one character at a time.
Q2.7 Write a program using loops to display the following:
*#*#*# #*#*#* *#*#*# #*#*#* *#*#*# #*#*#*
You may display only one character at a time.
Q2.8 Write a program using loops to display the following:
* * * * * * * * * * * *
You may display only one character at a time.
Q2.9 Write a program to display the following:
******** *######* *#$$$$#* *#$@@$#* *#$$$$#* *######* ********
You may print only one character at a time.
2.10 Write a drawing program that plots the line y=x^2+1 (i.e. y equals x squared plus 1) as a series of points. Display the x and y axes with labels. Don't use the drawLine command.
Hints: Use a loop. A point is a 1x1 rectangle. Remember that on the window co-ordinate system (0,0) is top left but you want to plot from bottom left.
Q2.11 Write a drawing program to plot an oval using a series of points.
Hint: class Math in the Java class libraries implements functions like sin, cos and tan. The expression Math.sin(x) will calculate the sin of x (but note that it works with radians not degrees).
Q2.12 Write a drawing program to plot a cone-shaped spiral using a series of points, like this:
Hint: If you can draw a circle, just keep increasing the radius and shifting along the x-axis. Try drawing a simple circle first, then do a spiral and final modify the program to draw the cone shape.
Q2.13 Write a method to display triangles of characters like the following:
* # ** ## *** ###
**** #### ***** and #####
The method parameters should be the width of the base of the triangle, the character used to display the triangle and whether the triangle should face left or right. Use the method in a test program to display a variety of triangles.